package pct.topic;

import java.util.LinkedList;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;
import pct.entity.Topic;
import pct.manage.StatusManager;
import pct.page.PageFilter;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class AccessTopics extends ActionSupport implements SessionAware,
		Preparable {
	private String selectedGroupName;
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;
	private boolean isJoined = false;

	public String getSelectedGroupName() {
		return selectedGroupName;
	}

	public void setSelectedGroupName(String selectedGroupName) {
		this.selectedGroupName = selectedGroupName;
	}

	public String execute() {
		// fetch the status manager from session map
		// update its relatedTopics property due to the group user selects
		StatusManager sm = (StatusManager) session.get("status");
		PageFilter pf = new PageFilter();
		LinkedList<Topic> tt = pf.getFirstPageTopics(selectedGroupName);
		if(tt!=null)
		{
			for(Topic i : tt) {
				i.setPostNumber(pcService.retrievePostNumber(i.getTopicID()));
			}
		}
		sm.setRelatedTopics(tt);
		// sm.setRelatedTopics(pcService.getRelatedTopics(selectedGroupName));
		sm.setCurrentGroupName(selectedGroupName);
		sm.setPageType(2);
		sm.setCurrentPage(1);
		isJoined = pcService.isJoined(sm.getCurrentUser().getUsername(), selectedGroupName);
		sm.setJoined(isJoined);
		session.put("status", sm);
		return SUCCESS;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}

	public boolean isJoined() {
		return isJoined;
	}

	public void setJoined(boolean isJoined) {
		this.isJoined = isJoined;
	}
}
